import React, { useState, useEffect } from 'react';
import ContentTitle from "@/components/contentTitle/ContentTitle";
import {  Button, Form, Input, InputNumber, Upload, TimePicker, message, Checkbox, Image } from 'antd';
import {  PlusOutlined } from '@ant-design/icons';
import { getShopDetail,saveShop } from "@/api/shop";
import { baseUrl } from "@/utile/commen.js";
import dayjs from 'dayjs';

export default function ShopInfo() {
  const [previewOpen, setPreviewOpen] = useState(false);
  const [previewImage, setPreviewImage] = useState('');
  const [info, setInfo] = useState({
    id: null,
    name: '',
    bulletin: '',
    avatar: '',
    deliveryPrice: null,
    deliveryTime: null,
    description: '',
    score: '',
    sellCount: null,
    supports: [],
    pics: [],
    date: [],
    minPrice: ''
  });
  const [imgUrl, setImgUrl] = useState('');
  const [fileList, setFileList] = useState([]);
  const plainOptions = ['单人精彩套餐', 'VC无限橙果汁全场8折', '在线支付满28-5', '特价饮品八折抢购', '中秋特惠', '国庆特价', '春节1折折扣'];
  const getInfo = async () => {
    const { data } = await getShopDetail();
    // 处理图片列表
    data.pics = data.pics.map(item => {
      return {
        url: baseUrl + item
      };
    });
    // 处理日期列表
    data.date = data.date.map(item => {
      return dayjs(item);
    });
    setImgUrl( data.avatar);
    setInfo(data);
    setFileList(data.pics);
  };

  useEffect(() => {
    getInfo();
  }, []);

  const handlePreview = async (file) => {
    if (!file.url && !file.preview) {
      file.preview = await getBase64(file.originFileObj);
    }
    setPreviewImage(file.url || file.preview);
    setPreviewOpen(true);
  };

  const handleChange = ({ fileList: newFileList }) => setFileList(newFileList);
  const handleChange1 = (info) => {
    if (info.file.status === 'done') {
      console.log(info.file);
      // 处理图片路径
      const index = info.file.response.imgUrl.lastIndexOf('/');
      const processedImgUrl = '/upload/shop/'+info.file.response.imgUrl.slice(index + 1);
      setImgUrl(processedImgUrl);
      message.success('图片上传成功');
    }
    if (info.file.status === 'error') {
      message.error('图片上传失败');
    }
  };
  const uploadButton = (
    <button style={{ border: 0, background: 'none' }} type="button">
      <PlusOutlined />
      <div style={{ marginTop: 8 }}>Upload</div>
    </button>
  );
  const onFinish = async (values) => {
    console.log(fileList);
    values.date = values.date.map(item => {
      return dayjs(item).format('YYYY-MM-DD HH:mm:ss');
    });
    const newInfor = {...info,...values};
    //处理图片列表
    if (fileList) {
      newInfor.pics = fileList.map((item) => {
        let processedImgUrl = '';
        if (item.response) {
          const index = item.response.imgUrl.lastIndexOf('/');
          processedImgUrl = item.response.imgUrl.slice(index + 1);
        }
        else {
          const index = item.url.lastIndexOf('/');
          processedImgUrl = item.url.slice(index + 1);
        }
        // // const index = item.response.imgUrl.lastIndexOf('/');
        // // const processedImgUrl = item.response.imgUrl.slice(index + 1);
        return processedImgUrl;
      });
    } else {
      newInfor.pics = [];
    }
    newInfor.pics = JSON.stringify(newInfor.pics);
    //处理头像
    const index = imgUrl.lastIndexOf('/');
    newInfor.avatar = imgUrl.slice(index + 1);
    //处理时间
    newInfor.date = JSON.stringify(values.date);
    //处理多选
    newInfor.supports = JSON.stringify(values.supports);
    // console.log(newInfor);
    
    const {code,msg} = await saveShop(newInfor);
    if (code === 0) {
      getInfo();
      message.success(msg);
    } else {
      message.error(msg);
    }
  }

  return (
    <>
      <ContentTitle title="店铺管理">

      </ContentTitle>
      {info.id ? (
        <Form name='shopInfo' labelCol={{ span: 2 }} wrapperCol={{ span: 18 }} style={{ width: '100%', marginTop: 20 }} initialValues={info} onFinish={onFinish}>
          <Form.Item label="店铺名称" name={"name"}>
            <Input style={{ width: '100%' }} />
          </Form.Item>
          <Form.Item label="店铺公告" name={"bulletin"}>
            <Input.TextArea style={{ width: '100%' }} rows={4} />
          </Form.Item>
          <Form.Item label="店铺头像" name={"avatar"}>
            <div>
              <Upload
                listType="picture-card"
                className="avatar-uploader"
                showUploadList={false}
                action={'/poo/shop/upload'}
                onChange={handleChange1}
              >
                {imgUrl ? (
                  <img src={baseUrl + imgUrl} alt="avatar" style={{ width: '100%', height: '100%' }} />
                ) : (
                  uploadButton
                )}
              </Upload>
            </div>
          </Form.Item>
          <Form.Item label="店铺图片" name={"pics"}>
            <div>
              <Upload
                listType="picture-card"
                fileList={fileList}
                onPreview={handlePreview}
                onChange={handleChange}
                action={'/poo/shop/upload'}
              >
                {fileList.length >= 8 ? null : uploadButton}
              </Upload>
              {previewImage && (
                <Image
                  wrapperStyle={{ display: 'none' }}
                  preview={{
                    visible: previewOpen,
                    onVisibleChange: (visible) => setPreviewOpen(visible),
                    afterOpenChange: (visible) => !visible && setPreviewImage(''),
                  }}
                  src={previewImage}
                />
              )}
            </div>
          </Form.Item>
          <Form.Item label="起送价格" name={"deliveryPrice"}>
            <InputNumber style={{ width: '100%' }} />
          </Form.Item>
          <Form.Item label="送达时间" name={"deliveryTime"}>
            <InputNumber style={{ width: '100%' }} />
          </Form.Item>
          <Form.Item label="配送描述" name={"description"}>
            <Input style={{ width: '100%' }} />
          </Form.Item>
          <Form.Item label="店铺好评率" name={"score"}>
            <InputNumber style={{ width: '100%' }} />
          </Form.Item>
          <Form.Item label="店铺销量" name={"sellCount"}>
            <InputNumber style={{ width: '100%' }} />
          </Form.Item>
          <Form.Item label="活动支持" name={"supports"}>
            <Checkbox.Group options={plainOptions} />
          </Form.Item>

          <Form.Item label="营业时间" name={"date"}>
            <TimePicker.RangePicker format={"HH:mm:ss"} />
          </Form.Item>
          <Form.Item style={{ marginLeft: '50px' }}>
            <Button type='primary' htmlType='submit'>保存店铺信息</Button>
          </Form.Item>
        </Form>
      ) : null}
    </>
  );
}    